package com.zapi.ai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zapi.ai.mapper.AiChatHistoryMapper;
import com.zapi.ai.model.ChatMessage;
import com.zapi.ai.model.entity.AiChatHistory;
import com.zapi.ai.service.AiChatHistoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * AI聊天历史服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AiChatHistoryServiceImpl implements AiChatHistoryService {
    
    private final AiChatHistoryMapper chatHistoryMapper;
    private final ObjectMapper objectMapper;
    
    @Override
    public void saveMessage(String userId, String sessionId, ChatMessage message, String model, Integer tokens) {
        try {
            AiChatHistory history = new AiChatHistory();
            history.setUserId(userId);
            history.setSessionId(sessionId);
            history.setRole(message.getRole());
            history.setContent(message.getContent());
            history.setModel(model);
            history.setTokens(tokens);
            history.setCreateTime(LocalDateTime.now());
            
            // 转换图片和文件为JSON
            if (message.getImages() != null && !message.getImages().isEmpty()) {
                history.setImages(objectMapper.writeValueAsString(message.getImages()));
            }
            if (message.getFiles() != null && !message.getFiles().isEmpty()) {
                history.setFiles(objectMapper.writeValueAsString(message.getFiles()));
            }
            
            chatHistoryMapper.insert(history);
            log.debug("保存聊天历史成功: userId={}, sessionId={}", userId, sessionId);
        } catch (JsonProcessingException e) {
            log.error("保存聊天历史失败", e);
        }
    }
    
    @Override
    public List<ChatMessage> getUserHistory(String userId, int limit) {
        LambdaQueryWrapper<AiChatHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiChatHistory::getUserId, userId)
               .orderByDesc(AiChatHistory::getCreateTime)  // 先降序查询最新的N条
               .last("LIMIT " + limit);
        
        List<ChatMessage> messages = convertToMessages(chatHistoryMapper.selectList(wrapper));
        
        // 反转顺序，使旧消息在前，新消息在后
        java.util.Collections.reverse(messages);
        
        return messages;
    }
    
    @Override
    public List<ChatMessage> getSessionHistory(String sessionId) {
        LambdaQueryWrapper<AiChatHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiChatHistory::getSessionId, sessionId)
               .orderByAsc(AiChatHistory::getCreateTime);
        
        return convertToMessages(chatHistoryMapper.selectList(wrapper));
    }
    
    @Override
    public void clearSessionHistory(String sessionId) {
        LambdaQueryWrapper<AiChatHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiChatHistory::getSessionId, sessionId);
        chatHistoryMapper.delete(wrapper);
    }
    
    @Override
    public void clearUserHistory(String userId) {
        LambdaQueryWrapper<AiChatHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiChatHistory::getUserId, userId);
        chatHistoryMapper.delete(wrapper);
    }
    
    private List<ChatMessage> convertToMessages(List<AiChatHistory> historyList) {
        return historyList.stream()
                .map(h -> {
                    ChatMessage msg = new ChatMessage(h.getRole(), h.getContent());
                    msg.setTimestamp(h.getCreateTime().atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli());
                    
                    // 解析图片和文件
                    try {
                        if (h.getImages() != null && !h.getImages().isEmpty()) {
                            msg.setImages(objectMapper.readValue(h.getImages(), List.class));
                        }
                        if (h.getFiles() != null && !h.getFiles().isEmpty()) {
                            msg.setFiles(objectMapper.readValue(h.getFiles(), List.class));
                        }
                    } catch (JsonProcessingException e) {
                        log.warn("解析历史消息附件失败", e);
                    }
                    
                    return msg;
                })
                .collect(Collectors.toList());
    }
}

